const { User } = require("../model");
const { jwtSecret } = require("../config/config.default");
const jwt = require("../util/jwt");

// 用户注册
exports.register = async (req, res, next) => {
  try {
    // 1、获取请求提数据
    console.log(req.body);
    // 2、数据验证
    // 3、数据存储
    var user = new User(req.body.user);
    await user.save();
    // 删除返回的密码
    user = user.toJSON();
    delete user.password;

    //4、发送成功响应
    res.status(201).json({ user });
  } catch (error) {
    next(error);
  }
};

// 用户登录
exports.login = async (req, res, next) => {
  try {
    const user = req.user.toJSON();
    const token = await jwt.sign(
      {
        userId: user._id,
      },
      jwtSecret,
      { expiresIn: 60 * 60 * 24 }
    );
    delete user.password;
    res.status(500).json({ ...user, token });
  } catch (error) {
    next(error);
  }
};

// 获取当前登录用户
exports.getCurrentUser = async (req, res, next) => {
  try {
    // const user = req.user.toJSON();
    // delete user.password;
    res.status(200).json({ user: req.user });
  } catch (error) {
    next(error);
  }
};

// 更新当前用户
exports.uploadCurrentUser = async (req, res, next) => {
  try {
    const user = await User.findOneAndUpdate(
      { email: req.body.user.email },
      req.body.user
    );
    //4、发送成功响应
    res.status(201).json(user);
  } catch (error) {
    next(error);
  }
};
